<template>
  <div>
    <div>
      <div>
        <!--这里放按钮-->
        <el-button v-for="item in buttonList" :key="item.click" :type="item.type" :icon="item.icon" style="margin-bottom: 10px" @click="buttonClick(item.click)">{{ item.clickName }}</el-button>
      </div>
      <div>
        <!--这里是table-->
        <el-table v-loading="listLoading" :data="sourceData" border @selection-change="handleSelectionChange" @select="handleSelect" @select-all="handleSelectAll">
          <slot></slot>
        </el-table>
      </div>
    </div>
    <div>
      <!--分页-->
      <el-pagination
        style="float: right;margin-top:20px"
        :page-size="tablePageSize"
        :page-sizes="[10, 20, 50, 100]"
        :current-page.sync="pageIndex"
        :total="sourceTotal"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HlTable',
  props: {
    dataUrl: {
      type: String,
      default: ''
    },
    queryForm: {
      type: Object,
      default: null
    },
    buttonList: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      tablePageSize: 20,
      pageIndex: 1,
      sourceTotal: 0,
      sourceData: [],
      listLoading: false,
      checkboxData: [] // 选中的数据
    }
  },
  created() {
    this.getTable(1, 20)
  },
  methods: {
    // 每页 ${val} 条
    handleSizeChange(val) {
      this.tablePageSize = val
      this.getTable(1, val)
    },
    // 当前页: ${val} 页
    handleCurrentChange(val) {
      this.pageIndex = val
      this.getTable(val, this.tablePageSize)
    },
    /** 当用户手动勾选数据行的 Checkbox 时触发的事件
    * row是当前选中的行，val是选中的行，可能有多行
    * */
    handleSelect(val, row) {
      this.checkboxData = val
    },
    /* 当用户手动勾选全选 Checkbox 时触发的事件	*/
    handleSelectAll(val) {
      this.checkboxData = val
    },
    /* 当选择项发生变化时会触发该事件 */
    handleSelectionChange() {
    },
    // 按钮方法
    buttonClick(click) {
      // 向调用者，“抛出”一个方法
      this.$emit(click, this.checkboxData)
    },
    // 获取表格数据
    getTable(index, size) {
      const param = {
        pageIndex: index || 1,
        pageSize: size || 20
      }
      this.tablePageSize = size || 20
      this.pageIndex = index || 1
      if (this.queryForm) {
        for (const attr in this.queryForm) {
          param[attr] = this.queryForm[attr]
        }
      }
      this.listLoading = true
      this.$http.get(this.dataUrl, param).then(res => {
        if (res) {
          this.sourceData = res.list
          this.sourceTotal = res.total
        }
        this.listLoading = false
      }).catch(errer => {
        this.$message.error(errer.message)
        this.listLoading = false
      })
    }
  }
}
</script>

<style scoped>
</style>

